package com.cskaoyan.controller;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.User;
import com.cskaoyan.exception.CustomValidationException;
import com.cskaoyan.util.ValidationUtil;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Date;

/**
 * @author stone
 * @date 2021/11/24 11:25
 */
@RestController
@RequestMapping("user")
public class UserController {

    //localhost:8080/user/register?username=songge&password=niupi&age=30&birthday=1991/11/24
    @RequestMapping("register")
    public BaseRespVo register(String username, String password, Integer age, Date birthday) {
        if (username == null || username.length() < 6) {
            return BaseRespVo.fail("用户名过短");
        }
        if (password == null || password.length() < 6) {
            return BaseRespVo.fail("密码太短了");
        }
        if (age == null || age < 18) {
            return BaseRespVo.fail("防沉迷");
        }
        if (birthday.compareTo(new Date()) > 0) {
            return BaseRespVo.fail("你不能在将来的某一天出生");
        }
        return BaseRespVo.ok(null);
    }

    //localhost:8080/user/register?username=songge&password=niupi&age=30&birthday=1991/11/24
    @RequestMapping("register2")
    public BaseRespVo register2(@Valid User user, BindingResult bindingResult) {

        //成员变量中是否有不满足校验逻辑的 → 只要有一个不满足就返回true
        if (bindingResult.hasFieldErrors()) {
            //成员变量错误 → 请求参数的错误
            FieldError fieldError = bindingResult.getFieldError();
            //拒绝值，也就是你因为传入了什么值导致了校验失败
            Object rejectedValue = fieldError.getRejectedValue();
            //成员变量名 → 请求参数名
            String field = fieldError.getField();
            String defaultMessage = fieldError.getDefaultMessage();
            String message = "请求参数" + field + "因为传入了值"
                    + rejectedValue + "导致校验失败：" + defaultMessage;
            return BaseRespVo.paramError(message);
        }
        return BaseRespVo.ok(null);
    }

    //localhost:8080/user/register3?username=songge&password=niupi&age=30&birthday=1991/11/24
    @RequestMapping("register3")
    public BaseRespVo register3(@Valid User user, BindingResult bindingResult) {

        //成员变量中是否有不满足校验逻辑的 → 只要有一个不满足就返回true
        if (bindingResult.hasFieldErrors()) {
            return ValidationUtil.valid(bindingResult);
        }
        return BaseRespVo.ok(null);
    }

    //localhost:8080/user/register4?username=songge&password=niupi&age=30&birthday=1991/11/24
    @RequestMapping("register4")
    public BaseRespVo register4(@Valid User user, BindingResult bindingResult) throws CustomValidationException {

        ValidationUtil.valid2(bindingResult);

        return BaseRespVo.ok(null);
    }

}
